﻿@using Domain
@model IList<Department>
@{
	Layout = null;
}

<link href="~/dist/layui/css/layui.css" rel="stylesheet" />
<div class="layui-fluid">
	<div>
		<table class="layui-table">
			<colgroup>
				<col width="150">
				<col width="150">
				<col width="200">
				<col>
			</colgroup>
			<thead>
				<tr>
					<th>部门名称</th>
					<th>上级部门</th>
					<th>排序</th>
				</tr>
			</thead>
			<tbody>
				@foreach (var item in Model)
				{
					<tr id="js-tr-@item.ID">
						<td>@item.Name</td>
						<td>@(item.ParentDept == null ? "一级部门" : item.ParentDept.Name)</td>
						<td>
							<div class="layui-btn-group">
								<button class="layui-btn" onclick="onUp(this)"><i class="layui-icon layui-icon-up"></i></button>
								<button class="layui-btn" onclick="onDown(this)"><i class="layui-icon layui-icon-down"></i></button>
							</div>
						</td>
					</tr>
				}
			</tbody>
		</table>
	</div>
	<div>
		<form>
			<input id="js-ids" name="ids" type="hidden" />
			<div class="layui-form-item">
				<div class="layui-input-block">
					<button class="layui-btn" onclick="return saveData();">保存</button>
				</div>
			</div>
		</form>
	</div>
</div>
<script src="~/Scripts/jquery-1.12.0.min.js"></script>
<script src="~/dist/layui/layui.js"></script>
<script>

	function onUp(obj) {
		$currentTr = $(obj).parent().parent().parent('tr');
		$currentTr.insertBefore($currentTr.prev('tr'));
		updateSortIds();
	}

	function onDown(obj) {
		$currentTr = $(obj).parent().parent().parent('tr');
		$currentTr.insertAfter($currentTr.next('tr'));
		updateSortIds();
	}

	function saveData() {
		$.ajax({
			type: "post",
			url: "/Admin/Department/Sort",
			data: $("form").serialize(),
			dataType: "json",
			success: function (data) {
				if (data.code > 0) {
					console.log("保存成功");
					// 3.关闭弹窗
					parent.layer.close(parent.layer.index);
					window.parent.location.reload();
				} else if (data.code < 0) {
					// 失败
					layer.msg(data.message);
				}
			}
		});
		return false;
	}

	function updateSortIds() {
		var $trs = $('table tbody tr');
		var ids = '';
		for (var i = 0; i < $trs.length; i++) {
			var idVal = $($trs[i]).attr('id');
			ids += parseInt(idVal.substring(idVal.lastIndexOf('-') + 1)) + ',';
		}
		$('#js-ids').val(ids);
	}

	var form, layer;
	layui.use(['form', 'layer'], function () {
		form = layui.form,
			layer = layui.layer;
	});

	$(function () {
		updateSortIds();
	});
</script>
